<?php
// +----------------------------------------------------------------------
// | 文章详情接口
// +----------------------------------------------------------------------

namespace api\portal\controller;

use api\portal\model\PortalPostModel;
use api\user\model\UserFavoriteModel;
use api\user\model\UserLikeModel;
use cmf\controller\RestBaseController;
use think\Db;

class ArticlesController extends RestBaseController {
	protected $postModel;

	public function __construct(PortalPostModel $postModel) {
		parent::__construct();
		$this->postModel = $postModel;
	}

	/**
	 * [index description]
	 * @param int $page 分页参数
	 * @param int $limit 每页条数
	 * @return [type] [description]
	 */
	public function index() {
		$params = $this->request->get();
		$params['where']['post_type'] = 1;

		$params['relation'] = 'user';
		$params['relation'] = 'categories';

		$params['order'] = '-create_time';

		$data = $this->postModel->getDatas($params);

		foreach ($data as $key => $value) {
			$data[$key]['friendly_time'] = func_friendly_time($value['create_time']);

			//若果摘要为空，从内容中提取
			if (empty($value['post_excerpt'])) {
				$data[$key]['post_excerpt'] = str_replace("\n", "", strip_tags($value['post_content']));
			}

			//若果标题为空，设置标题默认值
			if (empty($value['post_title'])) {
				$data[$key]['post_title'] = $data[$key]['post_excerpt'];
			}

			//若果来源为空，设置默认值
			if (empty($value['post_source'])) {
				$data[$key]['post_source'] = "梅陇客栈";
			}

			//若果昵称为空，用用户代表昵称
			if (empty($value['user']['user_nickname'])) {
				$data[$key]['user_nickname'] = empty($value['user']['user_login']) ? "未设置" : $value['user']['user_login'];
			} else {
				$data[$key]['user_nickname'] = $value['user']['user_nickname'];
			}
		}

		if (empty($this->apiVersion) || $this->apiVersion == '1.0.0') {
			$response = $data;
		} else {
			$response = ['list' => $data];
		}

		$this->success('请求成功!', $response);
	}

	/**
	 * 获取指定的文章
	 * @param int $id
	 */
	public function read() {
		$id = $this->request->get('id');

		if (intval($id) === 0) {
			$this->error('无效的文章id！');
		} else {
			$params = $this->request->get();
			$params['where']['post_type'] = 1;
			$params['id'] = $id;
			$params['relation'] = 'user';
			$data = $this->postModel->getDatas($params);
			if (empty($data)) {
				$this->error('文章不存在！');
			} else {
				$this->postModel->where('id', $id)->setInc('post_hits');
				$url = cmf_url('portal/Article/index', ['id' => $id, 'cid' => $data['categories'][0]['id']], true, true);

				$data = $data->toArray();
				$data['url'] = $url;
				$data['friendly_time'] = date('Y年m月d日 H:s', $data['create_time']);

				$data['post_content'] = str_replace("\n", "<br>", strip_tags($data['post_content'], "<img>"));

				if (substr($data['post_content'], 0, 4) !== '<br>') {
					$data['post_content'] = "<br>" . $data['post_content'];
				}

				if (!empty($data['more']['photos'])) {
					// var_dump($data['more']['photos']);
					// $data['post_content'] .= '<br>';
					foreach ($data['more']['photos'] as $key => $value) {
						$data['post_content'] .= "<br><br><img src='" . $value['url'] . "'>";
					}
				}

				//若果摘要为空，从内容中提取
				if (empty($data['post_excerpt'])) {
					$data['post_excerpt'] = str_replace("\n", "", strip_tags($data['post_content']));
				}

				//若果来源为空，设置默认值
				if (empty($data['post_source'])) {
					$data['post_source'] = "梅陇客栈";
				}

				//若果昵称为空，用用户代表昵称
				if (empty($data['user']['user_nickname'])) {
					$data['user_nickname'] = empty($data['user']['user_login']) ? "未设置" : $data['user']['user_login'];
				} else {
					$data['user_nickname'] = $data['user']['user_nickname'];
				}

				$this->success('请求成功!', $data);
			}

		}
	}

	/**
	 * 我的文章列表
	 */
	public function my() {
		$params = $this->request->get();
		$userId = $this->getUserId();

		$params['order'] = '-create_time';

		$data = $this->postModel->getUserArticles($userId, $params);

		foreach ($data as $key => $value) {
			$data[$key]['friendly_time'] = func_friendly_time($value['create_time']);

			//若果摘要为空，从内容中提取
			if (empty($value['post_excerpt'])) {
				$data[$key]['post_excerpt'] = str_replace("\n", "", strip_tags($value['post_content']));
			}

			//若果标题为空，设置标题默认值
			if (empty($value['post_title'])) {
				$data[$key]['post_title'] = $data[$key]['post_excerpt'];
			}

			//若果来源为空，设置默认值
			if (empty($value['post_source'])) {
				$data[$key]['post_source'] = "梅陇客栈";
			}

			//若果昵称为空，用用户代表昵称
			if (empty($value['user']['user_nickname'])) {
				$data[$key]['user_nickname'] = empty($value['user']['user_login']) ? "未设置" : $value['user']['user_login'];
			} else {
				$data[$key]['user_nickname'] = $value['user']['user_nickname'];
			}
		}

		if (empty($this->apiVersion) || $this->apiVersion == '1.0.0') {
			$response = $data;
		} else {
			$response = ['list' => $data];
		}

		$this->success('请求成功!', $response);
	}

	/**
	 * 添加文章
	 */
	public function save() {
		$post = file_get_contents('php://input', 'r');
		$data = json_decode($post, true);

		//获取用户登录信息
		$data['user_id'] = $this->getUserId();
		// $this->request->post();

		$result = $this->validate($data, 'Articles.article');
		if ($result !== true) {
			$this->error($result);
		}

		if (empty($data['published_time'])) {
			$data['published_time'] = time();
		}

		//保存图片信息
		if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
			$data['more']['photos'] = [];
			foreach ($data['photo_urls'] as $key => $url) {
				$photoUrl = cmf_asset_relative_url($url);
				array_push($data['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
			}
		}

		$this->postModel->addArticle($data);

		$this->success('添加成功！', $data);
	}

	/**
	 * 更新文章
	 * @param  int $id
	 */
	public function update($id) {
		$data = $this->request->put();
		$result = $this->validate($data, 'Articles.article');
		if ($result !== true) {
			$this->error($result);
		}
		if (empty($id)) {
			$this->error('无效的文章id');
		}
		$result = $this->postModel->editArticle($data, $id, $this->getUserId());
		if ($result === false) {
			$this->error('编辑失败！');
		} else {
			$this->success('编辑成功！');
		}
	}

	/**
	 * 删除文章
	 * @param  int $id
	 */
	public function delete($id) {
		if (empty($id)) {
			$this->error('无效的文章id');
		}
		$result = $this->postModel->deleteArticle($id, $this->getUserId());
		if ($result == -1) {
			$this->error('文章已删除');
		}
		if ($result) {
			$this->success('删除成功！');
		} else {
			$this->error('删除失败！');
		}
	}

	/**
	 * 批量删除文章
	 */
	public function deletes() {
		$ids = $this->request->post('ids/a');
		if (empty($ids)) {
			$this->error('文章id不能为空');
		}
		$result = $this->postModel->deleteArticle($ids, $this->getUserId());
		if ($result == -1) {
			$this->error('文章已删除');
		}
		if ($result) {
			$this->success('删除成功！');
		} else {
			$this->error('删除失败！');
		}
	}

	public function search() {
		$params = $this->request->get();
		if (!empty($params['keyword'])) {
			$params['where'] = [
				'post_type' => 1,
				'post_title|post_keywords|post_excerpt' => ['like', '%' . $params['keyword'] . '%'],
			];
			$data = $this->postModel->getDatas($params);

			foreach ($data as $key => $value) {
				$data[$key]['friendly_time'] = func_friendly_time($value['create_time']);

				//若果摘要为空，从内容中提取
				if (empty($value['post_excerpt'])) {
					$data[$key]['post_excerpt'] = str_replace("\n", "", strip_tags($value['post_content']));
				}

				//若果标题为空，设置标题默认值
				if (empty($value['post_title'])) {
					$data[$key]['post_title'] = $data[$key]['post_excerpt'];
				}

				//若果来源为空，设置默认值
				if (empty($value['post_source'])) {
					$data[$key]['post_source'] = "梅陇客栈";
				}

				//若果昵称为空，用用户代表昵称
				if (empty($value['user']['user_nickname'])) {
					$data[$key]['user_nickname'] = empty($value['user']['user_login']) ? "未设置" : $value['user']['user_login'];
				} else {
					$data[$key]['user_nickname'] = $value['user']['user_nickname'];
				}
			}

			if (empty($this->apiVersion) || $this->apiVersion == '1.0.0') {
				$response = $data;
			} else {
				$response = ['list' => $data];
			}

			$this->success('请求成功!', $response);
		} else {
			$this->error('搜索关键词不能为空！');
		}

	}

	/**
	 * 搜索热词
	 * @return [type] [description]
	 */
	public function getHotWord() {
		$data = ['校友', '化工', '招聘'];
		$this->success('请求成功!', $data);
	}

	/**
	 * 文章点赞
	 * @return [type] [description]
	 */
	public function doLike() {
		$userId = $this->getUserId();

		$articleId = $this->request->param('id', 0, 'intval');

		$article = $this->postModel->where(['id' => $articleId])->field('id,post_title,post_excerpt,more')->find();
		if (empty($article)) {
			$this->error('文章不存在！');
		}

		$this->postModel->where(['id' => $articleId])->setInc('post_like');

		$likeCount = $this->postModel->where('id', $articleId)->value('post_like');

		$this->success("赞好啦！", ['post_like' => $likeCount]);

	}

	// public function doLike() {
	// 	$userId = $this->getUserId();

	// 	$articleId = $this->request->param('id', 0, 'intval');

	// 	$userLikeModel = new UserLikeModel();

	// 	$findLikeCount = $userLikeModel->where([
	// 		'user_id' => $userId,
	// 		'object_id' => $articleId,
	// 	])->where('table_name', 'portal_post')->count();

	// 	if (empty($findLikeCount)) {
	// 		$article = $this->postModel->where(['id' => $articleId])->field('id,post_title,post_excerpt,more')->find();
	// 		if (empty($article)) {
	// 			$this->error('文章不存在！');
	// 		}

	// 		Db::startTrans();
	// 		try {
	// 			$this->postModel->where(['id' => $articleId])->setInc('post_like');
	// 			$thumbnail = empty($article['more']['thumbnail']) ? '' : $article['more']['thumbnail'];
	// 			$userLikeModel->insert([
	// 				'user_id' => $userId,
	// 				'object_id' => $articleId,
	// 				'table_name' => 'portal_post',
	// 				'title' => $article['post_title'],
	// 				'thumbnail' => $thumbnail,
	// 				'description' => $article['post_excerpt'],
	// 				'url' => json_encode(['action' => 'portal/Article/index', 'param' => ['id' => $articleId, 'cid' => $article['categories'][0]['id']]]),
	// 				'create_time' => time(),
	// 			]);
	// 			Db::commit();
	// 		} catch (\Exception $e) {
	// 			Db::rollback();

	// 			$this->error('点赞失败！');
	// 		}

	// 		$likeCount = $this->postModel->where('id', $articleId)->value('post_like');
	// 		$this->success("赞好啦！", ['post_like' => $likeCount]);
	// 	} else {
	// 		$this->error("您已赞过啦！");
	// 	}
	// }

	/**
	 * 取消文章点赞
	 */
	public function cancelLike() {
		$userId = $this->getUserId();

		$articleId = $this->request->param('id', 0, 'intval');

		$userLikeModel = new UserLikeModel();

		$findLikeCount = $userLikeModel->where([
			'user_id' => $userId,
			'object_id' => $articleId,
		])->where('table_name', 'portal_post')->count();

		if (!empty($findLikeCount)) {

			Db::startTrans();
			try {
				$this->postModel->where(['id' => $articleId])->setDec('post_like');
				$userLikeModel->where([
					'user_id' => $userId,
					'object_id' => $articleId,
				])->where('table_name', 'portal_post')->delete();
				Db::commit();
			} catch (\Exception $e) {
				Db::rollback();
				$this->error('取消点赞失败！');
			}

			$likeCount = $this->postModel->where('id', $articleId)->value('post_like');
			$this->success("取消点赞成功！", ['post_like' => $likeCount]);
		} else {
			$this->error("您还没赞过！");
		}
	}

	/**
	 * 文章收藏
	 * @throws \think\Exception
	 */
	public function doFavorite() {
		$userId = $this->getUserId();

		$articleId = $this->request->param('id', 0, 'intval');

		$userFavoriteModel = new UserFavoriteModel();

		$findFavoriteCount = $userFavoriteModel->where([
			'user_id' => $userId,
			'object_id' => $articleId,
		])->where('table_name', 'portal_post')->count();

		if (empty($findFavoriteCount)) {
			$article = $this->postModel->where(['id' => $articleId])->field('id,post_title,post_excerpt,more')->find();
			if (empty($article)) {
				$this->error('文章不存在！');
			}

			Db::startTrans();
			try {
				$this->postModel->where(['id' => $articleId])->setInc('post_favorites');
				$thumbnail = empty($article['more']['thumbnail']) ? '' : $article['more']['thumbnail'];
				$userFavoriteModel->insert([
					'user_id' => $userId,
					'object_id' => $articleId,
					'table_name' => 'portal_post',
					'thumbnail' => $thumbnail,
					'title' => $article['post_title'],
					'description' => $article['post_excerpt'],
					'url' => json_encode(['action' => 'portal/Article/index', 'param' => ['id' => $articleId, 'cid' => $article['categories'][0]['id']]]),
					'create_time' => time(),
				]);
				Db::commit();
			} catch (\Exception $e) {
				Db::rollback();

				$this->error('收藏失败！');
			}

			$favoriteCount = $this->postModel->where('id', $articleId)->value('post_favorites');
			$this->success("收藏好啦！", ['post_favorites' => $favoriteCount]);
		} else {
			$this->error("您已收藏过啦！");
		}
	}

	/**
	 * 取消文章收藏
	 */
	public function cancelFavorite() {
		$userId = $this->getUserId();

		$articleId = $this->request->param('id', 0, 'intval');

		$userFavoriteModel = new UserFavoriteModel();

		$findFavoriteCount = $userFavoriteModel->where([
			'user_id' => $userId,
			'object_id' => $articleId,
		])->where('table_name', 'portal_post')->count();

		if (!empty($findFavoriteCount)) {

			Db::startTrans();
			try {
				$this->postModel->where(['id' => $articleId])->setDec('post_favorites');
				$userFavoriteModel->where([
					'user_id' => $userId,
					'object_id' => $articleId,
				])->where('table_name', 'portal_post')->delete();
				Db::commit();
			} catch (\Exception $e) {
				Db::rollback();
				$this->error('取消失败！');
			}

			$favoriteCount = $this->postModel->where('id', $articleId)->value('post_favorites');
			$this->success("取消成功！", ['post_favorites' => $favoriteCount]);
		} else {
			$this->error("您还没收藏过！");
		}
	}

	/**
	 * 分享文章
	 * @return [type] [description]
	 */
	public function doShare() {
		// $userId = $this->getUserId();
		$articleId = $this->request->param('id', 0, 'intval');

		$article = $this->postModel->where(['id' => $articleId])->field('id,post_title,post_excerpt,more')->find();
		if (empty($article)) {
			$this->error('文章不存在！');
		}

		$this->postModel->where(['id' => $articleId])->setInc('post_share');

		$shareCount = $this->postModel->where('id', $articleId)->value('post_share');
		$this->success("分享成功！", ['post_share' => $shareCount]);

	}

	/**
	 * 相关文章列表
	 */
	public function relatedArticles() {
		$articleId = $this->request->param('id', 0, 'intval');
		$categoryId = Db::name('portal_category_post')->where('post_id', $articleId)->value('category_id');

		$articles = $this->postModel->alias('post')->join('__PORTAL_CATEGORY_POST__ category_post', 'post.id=category_post.post_id')
			->where(['post.delete_time' => 0, 'post.post_status' => 1, 'category_post.category_id' => $categoryId])
			->order(Db::raw('rand()'))
			->limit(5)
			->select();

		$this->success('success', ['list' => $articles]);
	}
}